const ws = new WebSocket(`ws://${location.host}/ws/chat`);
const hiddenUsers = new Set();
let allUsers = new Set();
const colorList = ["#ff4d4f", "#ffa940", "#ffec3d", "#52c41a", "#36cfc9", "#1890ff", "#722ed1"];

// WebSocket 消息处理
ws.onmessage = function(event) {
    const msg = JSON.parse(event.data);
    if (msg.type === "USER_LIST") {
        updateUserList(msg.users);
    } else {
        showMessage(msg);
    }
};

// 输入框回车发送
document.getElementById("messageInput").addEventListener("keydown", function (event) {
    if (event.key === "Enter" && !event.shiftKey) {
        event.preventDefault();
        sendText();
    }
});

// 页面加载时恢复昵称
window.addEventListener("DOMContentLoaded", () => {
    const savedName = localStorage.getItem("chat-username");
    if (savedName) document.getElementById("username").value = savedName;
});

// 输入框失去焦点时自动保存
document.getElementById("username").addEventListener("blur", () => {
    const name = document.getElementById("username").value.trim();
    if (name) localStorage.setItem("chat-username", name);
});

// 监听粘贴事件上传图片
document.addEventListener("paste", function (e) {
    const username = document.getElementById("username").value.trim();
    if (!username) return alert("请输入昵称");

    if (e.clipboardData && e.clipboardData.items) {
        for (let i = 0; i < e.clipboardData.items.length; i++) {
            const item = e.clipboardData.items[i];
            if (item.kind === "file" && item.type.startsWith("image/")) {
                const file = item.getAsFile();
                if (file) handleFileUpload(file, username);
            }
        }
    }
});

// 判断是否是代码内容
function isCodeContent(text) {
    const trimmed = text.trim();
    return trimmed.startsWith("{") || trimmed.startsWith("[") || trimmed.startsWith("<");
}

// 转义 HTML
function escapeHtml(str) {
    return str.replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#39;");
}

// 显示消息
function showMessage(msg) {
    if (hiddenUsers.has(msg.sender)) return;

    const chat = document.getElementById("chat");

    // 消息气泡
    const div = document.createElement("div");
    div.className = "message p-2 rounded-lg bg-gray-100 dark:bg-gray-700 max-w-[70%] break-words shadow";

    // 发送者
    const senderSpan = document.createElement("span");
    senderSpan.className = "sender font-semibold text-blue-600 dark:text-blue-400";
    senderSpan.textContent = msg.sender + ": ";

    // 消息内容
    const contentSpan = document.createElement("span");
    contentSpan.className = "content";

    if (msg.type === "TEXT") {
        if (isCodeContent(msg.content)) {
            contentSpan.innerHTML = `
            <pre class="overflow-x-auto whitespace-pre-wrap break-words p-2 bg-gray-200 dark:bg-gray-800 rounded">
                <code>${escapeHtml(msg.content)}</code>
            </pre>`;
        } else {
            const html = DOMPurify.sanitize(marked.parse(msg.content));
            const withLineBreaks = html.replace(/\n/g, "<br>");
            contentSpan.className = "break-words [overflow-wrap:anywhere]";
            contentSpan.innerHTML = withLineBreaks;
        }
    } else if (msg.type === "IMAGE") {
        const img = document.createElement("img");
        img.src = msg.content;
        img.className = "chat-image max-w-[200px] cursor-pointer rounded shadow-sm hover:shadow-md transition-all";
        img.onclick = () => {
            const overlay = document.getElementById("image-overlay");
            const overlayImg = document.getElementById("overlay-img");
            overlayImg.src = img.src;
            overlay.style.display = "flex";
        };
        contentSpan.appendChild(img);
    } else if (msg.type === "FILE") {
        const link = document.createElement("a");
        link.href = msg.content;
        link.target = "_blank";
        link.download = msg.fileName;
        link.className = "file-link text-blue-600 hover:underline break-all flex items-center gap-1";
        link.innerHTML = `📎 ${msg.fileName}`;
        contentSpan.appendChild(link);
    }

    div.appendChild(senderSpan);
    div.appendChild(contentSpan);

    chat.appendChild(div);

    // 滚动到底部
    chat.scrollTop = chat.scrollHeight;

    // 播放提示音
    playNotifySound();
}

// 关闭图片预览
document.getElementById("overlay-close").onclick = () => {
    document.getElementById("image-overlay").style.display = "none";
};
document.getElementById("image-overlay").onclick = (e) => {
    if (e.target.id === "image-overlay") document.getElementById("image-overlay").style.display = "none";
};

// 播放提示音
function playNotifySound() {
    const audio = document.getElementById("notify-sound");
    if (audio) {
        audio.currentTime = 0;
        audio.play().catch(() => console.warn("提示音被浏览器阻止"));
    }
}

// 发送文本
function sendText() {
    const username = document.getElementById("username").value.trim();
    if (!username) return alert("请输入昵称");
    const input = document.getElementById("messageInput");
    const text = input.value.trim();
    if (!text) return;

    ws.send(JSON.stringify({ type: "TEXT", sender: username, content: text }));
    input.value = "";
}

const uploadBtn = document.getElementById("uploadBtn");
const fileInput = document.getElementById("fileInput");

uploadBtn.onclick = () => fileInput.click(); // 先弹出文件选择框

fileInput.onchange = () => {
    const username = document.getElementById("username").value.trim();
    if (!username) return alert("请输入昵称");
    if (fileInput.files.length === 0) return alert("请选择文件");
    handleFileUpload(fileInput.files[0], username);
    fileInput.value = ""; // 清空文件输入，方便下次上传
};


// 处理文件上传
function handleFileUpload(file, username) {
    const formData = new FormData();
    formData.append("file", file);
    fetch("/upload", { method: "POST", body: formData })
        .then(res => res.text())
        .then(url => {
            const isImage = file.type.startsWith("image");
            ws.send(JSON.stringify({
                type: isImage ? "IMAGE" : "FILE",
                sender: username,
                content: url,
                fileName: file.name
            }));
        })
        .catch(() => alert("上传失败"));
}

// 拖拽上传
const chatBox = document.getElementById("chat");
chatBox.addEventListener("dragover", (e) => { e.preventDefault(); chatBox.classList.add("dragover"); });
chatBox.addEventListener("dragleave", (e) => chatBox.classList.remove("dragover"));
chatBox.addEventListener("drop", (e) => {
    e.preventDefault(); chatBox.classList.remove("dragover");
    const username = document.getElementById("username").value.trim();
    if (!username) return alert("请输入昵称");
    Array.from(e.dataTransfer.files).forEach(file => handleFileUpload(file, username));
});

// 更新用户列表
function updateUserList(users) {
    allUsers = new Set(users);
    const list = document.getElementById("online-users");
    list.innerHTML = "";

    users.forEach((user, index) => {
        const color = colorList[index % colorList.length];

        // 创建li
        const li = document.createElement("li");
        li.className = "user-entry";

        // 小圆点表示在线状态
        const dot = document.createElement("span");
        dot.className = "user-color-dot";
        dot.style.backgroundColor = color;

        // 用户名
        const nameSpan = document.createElement("span");
        nameSpan.className = "user-name";
        nameSpan.textContent = user;

        // 组装
        li.appendChild(dot);
        li.appendChild(nameSpan);

        list.appendChild(li);
    });
}



// 发送按钮点击事件
document.getElementById("sendBtn").onclick = sendText;